#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include <fcntl.h>
int use()
{
  int pipefd[2]={0};
  if(pipe(pipefd) != 0)
  {
       perror("pipe");
       return 1;
  }
  printf("pipe[0]:%d\n",pipefd[0]);
  printf("pipe[1]:%d\n",pipefd[1]);
  return 0;
}
int use1()
{
  int pipefd[2]={0};
  if(pipe(pipefd) != 0)
  {
       perror("pipe");
       return 1;
  }
  //子进程写入
  //0是读取，1是写入
  if(fork() == 0)
  {
    const char* msg = "hello world!";
    close(pipefd[0]);
    while(1)
    {
      write(pipefd[1],msg,strlen(msg));
      sleep(1);
    }
  }
  //父进程读取数据
  char buff[64] = {0};
  while(1)
  {
    sleep(1);
    close(pipefd[1]);
    ssize_t s = read(pipefd[0],buff,sizeof(buff)-1);
    if(s>0)
    {
      buff[s] = 0;
      printf("buff:%s\n",buff);
    }
    else if(s==0)
    {
      printf("father quie...\n");
      break;
    }
    else{
      perror("read");
      break;
    }
  }

  return 0;
}
int main()
{
  int pipefd[2] = {0};
  if(pipe(pipefd)!=0){
    perror("pipe");
    return 1;
  }
  int id = fork();
  if(id > 0)
  {
    //parent写入
    close(pipefd[0]);
    const char* msg = "i am father";
    while(1){
      sleep(1);
      write(pipefd[1],msg,strlen(msg));

    }
    printf("father quit...\n");
    return 0;
  }
  else if(id == 0)
  {
    //child读取
    close(pipefd[1]);
    char buff[64] = {0};
    while(1){
      sleep(1);
      ssize_t s = read(pipefd[0], buff, sizeof(buff)-1);
      
      if(s>0){
        buff[s] = 0;
        printf("i am child,i read:%s\n",buff);
      }
      else if(s==0){
        break;
      }
      else{
        break;
      }
    }

  }
  else{
    //error
  }

  return 0;
}
